<template>
  <div v-loading.fullscreen="loading">
    <el-row :gutter="10">
      <!-- <el-button
        type="success"
        size="large"
        @click="dialogDatas.emptyLightsOnBtnClick"
      >
        空位亮灯
      </el-button>
      <el-button
        type="info"
        size="large"
        @click="dialogDatas.emptyLightsOffBtnClick"
      >
        空位灭灯
      </el-button> -->
    </el-row>

    <el-row
      class="marginTop10"
      :gutter="10"
    >
      <el-col
        :span="24"
        style="text-align:left"
      >
        <!-- <el-input
          v-model="dialogDatas.filters.MATCODE"
          size="large"
          @change="getMatInfo"
          clearable
          @focus="focusFn"
          ref="matCodeInput"
        >
          <template #prepend>物料号</template>
        </el-input> -->

        <el-input
          v-model="dialogDatas.filters.LOCATIONID"
          size="large"
          @change="getLocationID('LOCATIONID')"
          clearable
          @focus="focusFn"
          ref="locationIDInput"
        >
          <template #prepend>盘号</template>
        </el-input>

        <!-- <el-input
          v-model="dialogDatas.filters.DATA2"
          size="large"
          @change="getLocationID('DATA2')"
          clearable
        >
          <template #prepend>绑定库位号</template>
        </el-input> -->

      </el-col>
    </el-row>

    <el-form
      :model="dialogDatas.currentData"
      class="marginTop10"
      size="large"
    >
      <el-form-item
        v-for="item in dialogDatas.formItems"
        :label="item.label"
      >
        <el-date-picker
          v-if="item.isDate"
          v-model="dialogDatas.currentData[item.value]"
          :disabled="item.disable"
          :type="item.dateOption ? item.dateOption.type : 'date'"
          :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
          :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
          :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
          :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
        />
        <el-switch
          v-else-if="item.isSwitch"
          v-model="dialogDatas.currentData[item.value]"
          :disabled="item.disable"
          inline-prompt
          active-text="启用"
          inactive-text="不启用"
          :active-value="item.trueValue"
          :inactive-value="item.falseValue"
        />
        <el-input
          v-else
          v-model="dialogDatas.currentData[item.value]"
          :disabled="item.disable"
        />
      </el-form-item>
      <div style="margin-bottom: 20px;">
        <!-- <el-button
          type="success"
          size="large"
          @click="dialogDatas.confirmBtnClick"
        >
          提交
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="dialogDatas.confirmBtnClick"
        >
          灭灯
        </el-button>
        <el-button
          size="large"
          @click="dialogDatas.currentData = {}"
        >
          清空
        </el-button> -->
      </div>
    </el-form>
  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import myAxios from '@/myAxios/myAxios';
import myAxiosTPX from '@/myAxios/myAxiosTPX';
import { showWarning } from '@/hooks/useMyMessageBox';
import { dayjs } from 'element-plus';
import myAxios193 from '@/myAxios/myAxios193';
import { baseUrl } from '@/myAxios/api.config';

export default {
  name: 'StockCheckView',
  setup () {
    let loading = ref(false);
    let matCodeInput = ref(null);
    let locationIDInput = ref(null);

    let dialogDatas = reactive({
      filters: {
        MATCODE: '',
        LOCATIONID: '',
        DATA2: '',
        QRCODE: '',
        EMPTY_STOCKS: [],

      },
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "LOCATIONID",
          "label": "库位号",
          "isDate": false,
          "disable": true,
        },
        // {
        //   "value": "HJID",
        //   "label": "货架号",
        //   "isDate": false,
        //   "disable": true,
        // },
        {
          "value": "MATCODE",
          "label": "物料号",
          "isDate": false,
          "disable": true,
        },
        {
          "value": "MATNAME",
          "label": "物料描述",
          "isDate": false,
          "disable": true,
        },
        {
          "value": "QTY",
          "label": "库存数量",
          "isDate": false,
          "disable": true,
        },
        // {
        //   "value": "ISLOCKED",
        //   "label": "是否锁定",
        //   "isDate": false,
        // },
        // {
        //   "value": "MATTYPE",
        //   "label": "物料类型",
        //   "isDate": false,
        //   "disable": true,
        // },
        // {
        //   "value": "DATA1",
        //   "label": "DATA1",
        //   "isDate": false
        // },
        // {
        //   "value": "DATA2",
        //   "label": "DATA2",
        //   "isDate": false
        // },
        {
          "value": "DATA2",
          "label": "绑定库位号",
          "isDate": false,
          "disable": true,
        },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   }
        // },
      ],
      confirmBtnClick: function () {
        if (!dialogDatas.currentData.LOCATIONID) {
          showWarning('库位号不能为空!');
          return;
        }
        loading.value = true;
        // let now = dayjs().format('YYYY/MM/DD HH:mm:ss');

        let params = `${dialogDatas.currentData.LOCATIONID}🈹${dialogDatas.currentData.HJID}` +
          `🈹${dialogDatas.currentData.MATCODE}🈹${dialogDatas.currentData.MATNAME}` +
          `🈹${dialogDatas.currentData.QTY}🈹${dialogDatas.currentData.ISLOCKED}` +
          `🈹${dialogDatas.currentData.MATTYPE}🈹${dialogDatas.currentData.DATA1}` +
          `🈹${dialogDatas.currentData.DATA2}🈹${dialogDatas.filters.QRCODE}🈹${1}`;

        let requestParamsArr = [params,];

        let bdparams = `${dialogDatas.currentData.DATA2}🈹${dialogDatas.currentData.HJID}` +
          `🈹${dialogDatas.currentData.MATCODE}🈹${dialogDatas.currentData.MATNAME}` +
          `🈹${dialogDatas.currentData.QTY}🈹${dialogDatas.currentData.ISLOCKED}` +
          `🈹${dialogDatas.currentData.MATTYPE}🈹${dialogDatas.currentData.DATA1}` +
          `🈹${dialogDatas.currentData.LOCATIONID}${dialogDatas.filters.QRCODE}🈹${1}`;

        if (dialogDatas.currentData.DATA2) {
          requestParamsArr.push(bdparams);
        }

        let dataContent = {
          requestName: '陈帅廷添加或修改贴片线库位信息',
          requestParamsArr: requestParamsArr,
          requestFactory: "Q902",
        };
        myAxios193.post('users/postMutipleRequests', JSON.stringify(dataContent)).then(res => {
          if (res.returnData.message.includes('全部成功')) {
            loading.value = false;
            //成功后灭灯
            sendLightSigns([
              { LOCATIONID: dialogDatas.currentData.LOCATIONID },
              { LOCATIONID: dialogDatas.currentData.DATA2 },
            ]);
            dialogDatas.currentData.oriDATA2 = dialogDatas.currentData.DATA2;
            // dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!',
            });
            matCodeInput.value.focus();
            // getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      lightOffBtnClick: function () {
        sendLightSigns([
          { LOCATIONID: dialogDatas.filters.LOCATIONID },
          { LOCATIONID: dialogDatas.filters.DATA2 },
        ]);
      },
      cancelBtnClick: function () {

      },
      emptyLightsOnBtnClick: function () {
        loading.value = true;
        // 空盘亮红灯
        myAxios.get('陈帅廷获取贴片线空盘库位', '').then(res => {
          console.log('res :>> ', res);
          dialogDatas.filters.EMPTY_STOCKS = res;

          sendLightSigns(res, 32);
          loading.value = false;
        });
      },
      emptyLightsOffBtnClick: function () {
        loading.value = true;
        // 空盘灭灯
        sendLightSigns(dialogDatas.filters.EMPTY_STOCKS,);
        loading.value = false;
      },
    });

    let sendLightSigns = async function (datas, colorNum = 0) {
      // loading.value = true;

      let dataContent = {
        "Details": [
        ]
      };
      let demo = {
        "LocationId": "L8354A2055",
        "LightColor": 0,
        "Twinkle": 0,
        "IsLocked": 0,
        "IsMustCollect": 0,
        "Quantity": 5,
        "SubText": "11",
        "BatchCode": "BatchCode",
        "Name": "Name",
        "R1": "第一行",
        "R2": "第二行",
        "R3": "第三行",
        "SubTitle": "副标题",
        "Title": "主标题",
        "Unit": "单位",
        "RelateToTower": true
      };
      for (let i = 0; i < datas.length; i++) {
        let el = datas[i];
        let detail = { ...demo, LocationId: el.LOCATIONID, LightColor: colorNum };
        dataContent.Details.push(detail);
      }
      if (dataContent.Details.length) {
        if (baseUrl == 'cstApi/') {
          console.log('result :>> ', dataContent.Details, '测试默认亮灭灯成功');
        }
        else {
          let result = await myAxiosTPX.post('api/Light/PostInfo/', JSON.stringify(dataContent));
          console.log('result :>> ', result);
        }
      }
      loading.value = false;
    };

    let getTableDatas = async function () {
      if (!dialogDatas.filters.LOCATIONID) {
        showWarning('领料单不能为空');
      }
      else {
        loading.value = true;

        let stockParams = `${dialogDatas.filters.LOCATIONID}`;
        let stockTable = await myAxios.get('陈帅廷获取贴片线库位信息', stockParams);

        let length = stockTable.length;
        if (length == 0) {
          showWarning('未查询到库位信息');
          loading.value = false;
        }
        else {
          dialogDatas.currentData = { ...stockTable[0] };
          loading.value = false;
        }
      }

    };

    let getMatInfo = async function () {
      if (!dialogDatas.filters.MATCODE) {
        showWarning('物料号不能为空');
      }
      else {
        loading.value = true;

        let matcode = dialogDatas.filters.MATCODE.split('@')[0];
        let number = dialogDatas.filters.MATCODE.split('@')[1];
        dialogDatas.filters.QRCODE = matcode + '@' + dialogDatas.filters.MATCODE.split('@')[2];
        console.log('dialogDatas.filters.MATCODE :>> ', dialogDatas.filters.MATCODE);
        console.log('number :>> ', number);
        console.log('dialogDatas.filters.QRCODE :>> ', dialogDatas.filters.QRCODE);

        let stockParams = `${matcode}`;
        let stockTable = (await myAxios.getSap('SAP根据物料号查询物料描述2', stockParams, '9911')).TableSet.ZB_DESCRIPTION;
        console.log('stockTable :>> ', stockTable);

        // let stockParams = `${matcode}`;
        // let stockTable = await myAxios.get('陈帅廷查询物料信息', stockParams);

        let length = stockTable.length;
        if (length == 0) {
          showWarning('未查询到物料信息');
          loading.value = false;
        }
        else {
          dialogDatas.currentData.MATCODE = matcode;
          dialogDatas.currentData.MATNAME = stockTable[0].DATA1;
          dialogDatas.currentData.QTY = number;
          loading.value = false;
          locationIDInput.value.focus();
        }
      }

    };

    let focusFn = function (event) {
      event.srcElement.setAttribute('readonly', 'readonly');
      setTimeout(() => {
        event.srcElement.removeAttribute('readonly');
      }, 200);

      // console.log('event :>> ', event);
    };


    let getLocationID = async function (key) {
      if (!dialogDatas.filters[key]) {
        showWarning('库位号不能为空');
      }
      else {
        if (key == 'LOCATIONID') {
          let requestName = `陈帅廷查询贴片线物料库位`;
          if (dialogDatas.currentData.LOCATIONID) {
            sendLightSigns([dialogDatas.currentData], 0);
          }

          let splitArr = dialogDatas.filters.LOCATIONID.split('@');
          if (splitArr.length == 3) {
            dialogDatas.filters.LOCATIONID = splitArr[0] + '@' + splitArr[2];
          }
          let kwInfoList = await myAxios.get(requestName, dialogDatas.filters.LOCATIONID);
          if (kwInfoList.length) {
            let resultItem = kwInfoList[0];
            if (dialogDatas.filters.LOCATIONID.includes('-')) {
              resultItem.LOCATIONID = resultItem.DIPID;
            }
            dialogDatas.currentData = { ...resultItem };
            sendLightSigns([resultItem], 96);
          }
          else {
            showWarning('该库位为空盘库位！');
          }
          //   let existEmpty = dialogDatas.filters.EMPTY_STOCKS.find(item => item.LOCATIONID == dialogDatas.filters.LOCATIONID);
          //   if (!existEmpty) {
          //     loading.value = false;
          //     showWarning('该库位为非空盘库位，不能绑定！');
          //     return;
          //   }
          //   let stockParams = `${dialogDatas.filters.LOCATIONID}`;
          //   let stockTable = await myAxios.get('陈帅廷获取贴片线库位信息', stockParams);

          //   let length = stockTable.length;
          //   if (length == 0) {
          //     showWarning('未查询到库位信息');
          //     loading.value = false;
          //   }
          //   else {
          //     // dialogDatas.currentData.LOCATIONID = stockTable[0].LOCATIONID;
          //     // dialogDatas.currentData.DATA2 = stockTable[0].DATA2;
          //     //  dialogDatas.currentData.oriDATA2 = stockTable[0].DATA2;

          //     dialogDatas.currentData = {
          //       ...stockTable[0],
          //       MATCODE: dialogDatas.currentData.MATCODE,
          //       MATNAME: dialogDatas.currentData.MATNAME,
          //       QTY: dialogDatas.currentData.QTY,
          //     };
          //     dialogDatas.currentData.oriDATA2 = stockTable[0].DATA2;

          //     sendLightSigns([
          //       { LOCATIONID: dialogDatas.currentData.LOCATIONID },
          //       { LOCATIONID: dialogDatas.currentData.DATA2 },
          //     ], 64);
          //     loading.value = false;
          //   }
        }
      }
    };

    onMounted(() => {
      // getTableDatas();
    });

    return {
      matCodeInput,
      locationIDInput,
      focusFn,

      getTableDatas,
      getMatInfo,
      getLocationID,
      loading,
      dialogDatas,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

